import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';

// API基础配置
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3002/api';

// 创建axios实例
const apiInstance: AxiosInstance = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000, // 30秒超时
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
apiInstance.interceptors.request.use(
  (config) => {
    // 添加认证token
    const token = localStorage.getItem('admin_token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    // 添加请求日志
    console.log(`🌐 API Request: ${config.method?.toUpperCase()} ${config.url}`, {
      params: config.params,
      data: config.data,
    });

    return config;
  },
  (error) => {
    console.error('❌ API Request Error:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
apiInstance.interceptors.response.use(
  (response: AxiosResponse) => {
    // 添加响应日志
    console.log(`✅ API Response: ${response.config.method?.toUpperCase()} ${response.config.url}`, {
      status: response.status,
      data: response.data,
    });

    return response.data; // 直接返回数据部分
  },
  (error) => {
    console.error('❌ API Response Error:', error);

    // 处理认证错误
    if (error.response?.status === 401) {
      // 清除token并重定向到登录页
      localStorage.removeItem('admin_token');
      window.location.href = '/login';
      return Promise.reject(new Error('认证失败，请重新登录'));
    }

    // 处理网络错误
    if (!error.response) {
      return Promise.reject(new Error('网络连接失败，请检查网络设置'));
    }

    // 处理服务器错误
    const errorMessage = error.response?.data?.message || error.message || '请求失败';
    return Promise.reject(new Error(errorMessage));
  }
);

// API工具类
class ApiService {
  /**
   * GET请求
   */
  async get<T = any>(url: string, params?: any): Promise<T> {
    return apiInstance.get(url, { params });
  }

  /**
   * POST请求
   */
  async post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return apiInstance.post(url, data, config);
  }

  /**
   * PUT请求
   */
  async put<T = any>(url: string, data?: any): Promise<T> {
    return apiInstance.put(url, data);
  }

  /**
   * PATCH请求
   */
  async patch<T = any>(url: string, data?: any): Promise<T> {
    return apiInstance.patch(url, data);
  }

  /**
   * DELETE请求
   */
  async delete<T = any>(url: string): Promise<T> {
    return apiInstance.delete(url);
  }

  /**
   * 上传文件
   */
  async upload<T = any>(url: string, formData: FormData): Promise<T> {
    return apiInstance.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  }

  /**
   * 下载文件
   */
  async download(url: string, filename?: string): Promise<void> {
    const response = await apiInstance.get(url, {
      responseType: 'blob',
    });

    // 创建下载链接
    const blob = new Blob([response]);
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = filename || 'download';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(downloadUrl);
  }

  /**
   * 设置认证token
   */
  setAuthToken(token: string): void {
    localStorage.setItem('admin_token', token);
  }

  /**
   * 清除认证token
   */
  clearAuthToken(): void {
    localStorage.removeItem('admin_token');
  }

  /**
   * 获取认证token
   */
  getAuthToken(): string | null {
    return localStorage.getItem('admin_token');
  }

  /**
   * 检查是否已认证
   */
  isAuthenticated(): boolean {
    return !!this.getAuthToken();
  }
}

// 导出API实例
const api = new ApiService();
export default api;

// 导出axios实例（用于特殊情况）
export { apiInstance };

// 导出API基础URL
export { API_BASE_URL };
